package com.example.service;

import com.example.entity.Customer;
import com.example.entity.Employee;
import com.example.entity.User;
import com.example.enums.UserTypeEnum;
import com.example.exception.CustomerException;
import com.example.mapper.CustomerMapper;
import com.example.mapper.EmployeeMapper;
import com.example.mapper.UserMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserService {

    @Resource
    UserMapper userMapper;
    @Resource
    CustomerMapper customerMapper;
    @Resource
    EmployeeMapper employeeMapper;
    public void add(User user) {
        User dbuser = userMapper.selectByUsername(user.getUsername());
        if(dbuser != null){
            throw new CustomerException("账号重复");
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.insert(user);

        if(user.getUserType().equals(UserTypeEnum.CUSTOMER.getRoleId())){
            Customer customer = new Customer();
            customer.setUserId(user.getUserId());
            customerMapper.insert(customer);
        }else{
            Employee employee = new Employee();
            employee.setUserId(user.getUserId());
            employee.setPhone(user.getPhone());
            employeeMapper.insert(employee);
        }
    }

    public void update(User user) {
        userMapper.updateById(user);
    }

    public List<User> selectAll(){
        return userMapper.selectAll();
    }

    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize) {
        // User user = TokenUtils.getCurrentUser();
        //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.selectAll();
        return PageInfo.of(list);
    }

    public void deleteById(Integer id) {
        userMapper.deleteById(id);
        customerMapper.deleteByUserId(id);
        employeeMapper.deleteByUserId(id);
    }

    public User selectById(Integer userId) {
        return userMapper.selectById(userId);
    }

    public void updatePassword(String oldPassword, String newPassword, String confirmPassword) {
        User currentUser = TokenUtils.getCurrentUser();
        if (!newPassword.equals(confirmPassword)){
            throw new CustomerException("两次输入的密码不一致");
        } else if (!currentUser.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
            throw new CustomerException("原密码输入错误");
        }
        currentUser.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
        userMapper.updateById(currentUser);
    }
}
